'use client';

import { useWallet, useConnection } from '@solana/wallet-adapter-react';
import { useState, useEffect } from 'react';

export function WalletDebugInfo() {
  const { publicKey, connected, connecting, wallet, disconnect } = useWallet();
  const { connection } = useConnection();
  const [debugInfo, setDebugInfo] = useState<{
    userAgent: string;
    isPhantom: boolean;
    phantomVersion?: string;
    solanaNetwork: string;
    rpcEndpoint: string;
    networkStatus: 'checking' | 'connected' | 'failed';
    lastError?: string;
  } | null>(null);

  useEffect(() => {
    const updateDebugInfo = async () => {
      const userAgent = navigator.userAgent;
      const phantomProvider = (window as { solana?: { isPhantom?: boolean; version?: string } })?.solana;
      const isPhantom = !!phantomProvider?.isPhantom;
      const phantomVersion = phantomProvider?.version;

      let networkStatus: 'checking' | 'connected' | 'failed' = 'checking';
      let lastError: string | undefined;

      try {
        await connection.getSlot();
        networkStatus = 'connected';
      } catch (error) {
        networkStatus = 'failed';
        lastError = error instanceof Error ? error.message : '未知错误';
      }

      setDebugInfo({
        userAgent,
        isPhantom,
        phantomVersion,
        solanaNetwork: process.env.NEXT_PUBLIC_SOLANA_NETWORK || 'unknown',
        rpcEndpoint: connection.rpcEndpoint,
        networkStatus,
        lastError,
      });
    };

    updateDebugInfo();
  }, [connection]);

  const handleForceReconnect = async () => {
    try {
      await disconnect();
      // 等待一秒后重新连接
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    } catch (error) {
      console.error('重连失败:', error);
    }
  };

  if (!debugInfo) {
    return null;
  }

  return (
    <div className="fixed top-4 left-4 bg-black bg-opacity-80 text-white p-4 rounded-lg text-xs max-w-sm z-50">
      <div className="mb-2 font-bold">🔧 钱包调试信息</div>
      
      <div className="space-y-1">
        <div>
          <span className="text-yellow-300">状态:</span>{' '}
          {connected ? '✅ 已连接' : connecting ? '🔄 连接中' : '❌ 未连接'}
        </div>
        
        <div>
          <span className="text-yellow-300">钱包:</span>{' '}
          {wallet?.adapter.name || '未选择'}
        </div>
        
        <div>
          <span className="text-yellow-300">Phantom:</span>{' '}
          {debugInfo.isPhantom ? `✅ v${debugInfo.phantomVersion}` : '❌ 未检测到'}
        </div>
        
        <div>
          <span className="text-yellow-300">网络:</span>{' '}
          {debugInfo.solanaNetwork}
        </div>
        
        <div>
          <span className="text-yellow-300">RPC:</span>{' '}
          <div className="break-all text-xs">{debugInfo.rpcEndpoint}</div>
        </div>
        
        <div>
          <span className="text-yellow-300">RPC状态:</span>{' '}
          {debugInfo.networkStatus === 'connected' && '✅ 正常'}
          {debugInfo.networkStatus === 'checking' && '🔄 检测中'}
          {debugInfo.networkStatus === 'failed' && '❌ 失败'}
        </div>

        {debugInfo.lastError && (
          <div>
            <span className="text-red-300">错误:</span>{' '}
            <div className="text-xs break-words">{debugInfo.lastError}</div>
          </div>
        )}

        {publicKey && (
          <div>
            <span className="text-yellow-300">地址:</span>{' '}
            <div className="text-xs break-all">
              {publicKey.toString().slice(0, 8)}...{publicKey.toString().slice(-8)}
            </div>
          </div>
        )}
        
        <div>
          <span className="text-yellow-300">浏览器:</span>{' '}
          <div className="text-xs break-words">
            {debugInfo.userAgent.includes('Chrome') && '🌐 Chrome'}
            {debugInfo.userAgent.includes('Firefox') && '🦊 Firefox'}
            {debugInfo.userAgent.includes('Safari') && '🧭 Safari'}
            {debugInfo.userAgent.includes('Edge') && '🔷 Edge'}
          </div>
        </div>
      </div>

      <div className="mt-3 space-y-1">
        <button
          onClick={handleForceReconnect}
          className="w-full bg-blue-600 hover:bg-blue-700 text-white px-2 py-1 rounded text-xs transition-colors"
        >
          🔄 强制重连
        </button>
        
        <button
          onClick={() => setDebugInfo(null)}
          className="w-full bg-gray-600 hover:bg-gray-700 text-white px-2 py-1 rounded text-xs transition-colors"
        >
          ❌ 关闭调试
        </button>
      </div>
    </div>
  );
}
